package com.xiaoqiang.proxy.assistant;

import com.xiaoqiang.proxy.Hello;
import com.xiaoqiang.proxy.HelloDefault;
import javassist.*;

/**
 * @author 小强
 * @since 2019/1/3 23:09
 */
public class AssistantProxy {

    public static void main(String[] args) throws CannotCompileException, IllegalAccessException, InstantiationException {
        ClassPool classPool = ClassPool.getDefault();
        CtClass ctClass = classPool.makeClass("com.xiaoqiang.proxy.HelloDefault");
        CtMethod ctMethod = CtNewMethod.make("public String say(String name) {\n" +
                "        System.out.println(\"hello \"+name);\n" +
                "        return \"hello \"+name;\n" +
                "    }", ctClass);
        ctMethod.insertBefore("System.out.println(\"before invoke\");");
        ctMethod.insertAfter("System.out.println(\"after invoke\");");
        ctClass.addMethod(ctMethod);

        Class c = ctClass.toClass();
        HelloDefault hello = (HelloDefault) c.newInstance();
        hello.say("王五");
    }
}
